package com.useeinfo.oa.modules.wuHanCommon.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.DataVO;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.enumerate.FieldType;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.AnalysisObjectList;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.vo.DateListVO;
import com.useeinfo.oa.modules.base.vo.TimeSegmentVO;
import com.useeinfo.oa.modules.wuHanCommon.base.dao.AutomaticTableDao;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.AutomaticDayData;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.AutomaticModel;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.AutomaticTable;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WuHanPoint;
import com.useeinfo.oa.modules.wuHanCommon.base.enums.MeterReadingEnum;
import com.useeinfo.oa.modules.wuHanCommon.base.result.ResultDto_Wh;
import com.useeinfo.oa.modules.wuHanCommon.base.result.ResultUtil_Wh;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class AutomaticTableBiz extends CrudBiz<AutomaticTableDao, AutomaticTable> {

    @Autowired
    private WuHanPointBiz wuHanPointBiz;
    @Autowired
    private AutomaticDayDataBiz automaticDayDataBiz;
    @Autowired
    private AutomaticModelBiz automaticModelBiz;

    /**
     * 自动抄表数据
     *
     * @param data
     * @return
     */
    @Transactional
    public synchronized ResultDto_Wh setRealTimeDataFromSite(JSONObject data) {
        JSONObject UpdateCounts = new JSONObject();
        UpdateCounts.put("UpdateCounts", 0);
        if (data == null) {
            return ResultUtil_Wh.error("数据为空", UpdateCounts);
        }
        JSONArray points = data.getJSONArray("point");
        JSONArray values = data.getJSONArray("value");
        if (CollectionUtils.isEmpty(points) || CollectionUtils.isEmpty(values)) {
            return ResultUtil_Wh.error("数据为空", UpdateCounts);
        }
        Date time = StringConverters.ToDateTime(data.getString("time"));
        TimeSegmentVO timeSegmentVO = getTimeSegment(time);
        if (timeSegmentVO == null) {
            return ResultUtil_Wh.error("数据异常", UpdateCounts);
        }
        Map<String, String> pointMap = new HashMap<>();
        JSONArray warningArray = data.getJSONArray("warningOfPoints");
        for (int i = 0; i < warningArray.size(); i++) {
            JSONObject jsonObject = warningArray.getJSONObject(i);
            JSONArray pointArray = jsonObject.getJSONArray("points");
            if (pointArray == null || pointArray.size() <= 0) {
                continue;
            }
            for (int j = 0; j < pointArray.size(); j++) {
                pointMap.put(pointArray.getString(j), jsonObject.getString("infoDetail"));
            }
        }
        List<AutomaticTable> automaticTableList = new ArrayList<>();
        StringBuilder errAllmsg = new StringBuilder();
        for (int i = 0; i < points.size(); i++) {
            String point = points.getString(i);
            WuHanPoint wuHanPoint = wuHanPointBiz.getWuHanPointByName(point);
            if (wuHanPoint == null) {
                errAllmsg.append(point).append("点位不存在").append(",");
                continue;
            }
            String value = values.getString(i);
            /*if (StringUtils.isBlank(value)) {
                errAllmsg.append(point).append("值不能为空").append(",");
                continue;
            }*/
            automaticTableList.add(new AutomaticTable(wuHanPoint, value, time, pointMap.keySet().contains(point), pointMap.get(point)));
        }
        if (errAllmsg.length() > 0) {
            return ResultUtil_Wh.error(errAllmsg.toString(), UpdateCounts);
        }
        automaticTableList.forEach(automaticTable -> {
            saveAutomaticDayData(automaticTable, timeSegmentVO);
            this.addOrUpdate(automaticTable);
        });
        UpdateCounts.put("UpdateCounts", automaticTableList.size());
        return ResultUtil_Wh.success(UpdateCounts);
    }

    /**
     * 保存到抄表
     *
     * @param automaticTable
     * @return
     */
    @Transactional
    public void saveAutomaticDayData(AutomaticTable automaticTable, TimeSegmentVO timeSegmentVO) {
        WuHanPoint wuHanPoint = CommonSugar.getTypedDefault(automaticTable.getWuHanPoint(), new WuHanPoint());
        if (StringUtils.isBlank(wuHanPoint.getRemark())) {
            return;
        }
        if (wuHanPoint.getWuHanUnit() == null || wuHanPoint.getWuHanUnit().getMeterReadingEnum() == null) {
            return;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("nowTime", timeSegmentVO.getTime());
        queryParam.getSqlMap().put("checkContent", wuHanPoint.getRemark());
        queryParam.getSqlMap().put("endTime", timeSegmentVO.getSegment() + "");
        queryParam.getSqlMap().put("meterReadingEnum", wuHanPoint.getWuHanUnit().getMeterReadingEnum().getCode());
        List<AutomaticDayData> automaticDayDataList = automaticDayDataBiz.findList(queryParam);
        AutomaticDayData automaticDayData;
        if (CollectionUtils.isEmpty(automaticDayDataList)) {
            automaticDayData = new AutomaticDayData();
            automaticDayData.setNowTime(StringConverters.ToDateOnly(timeSegmentVO.getTime()));
            QueryParam queryParam1 = new QueryParam();
            queryParam1.getSqlMap().put("checkContent", wuHanPoint.getRemark());
            queryParam1.getSqlMap().put("endTime", timeSegmentVO.getSegment() + "");
            queryParam1.getSqlMap().put("meterReadingEnum", wuHanPoint.getWuHanUnit().getMeterReadingEnum().getCode());
            List<AutomaticModel> automaticModels = automaticModelBiz.findList(queryParam1);
            if (CollectionUtils.isEmpty(automaticModels)) {
                return;
            }
            automaticDayData.setAutomaticModel(automaticModels.get(0));
            automaticDayData.setTimePoint(timeSegmentVO.getSegment());
        } else {
            automaticDayData = automaticDayDataList.get(0);
        }
        automaticDayData.setValue(automaticTable.getValue());
        automaticDayData.setAbnormal(automaticTable.isAbnormal());
        automaticDayDataBiz.addOrUpdate(automaticDayData);

    }

    /**
     * 判断报警时间是属于哪个时间段
     *
     * @return
     */
    public TimeSegmentVO getTimeSegment(Date time) {
        Integer num = StringConverters.ToInteger(DateTimeUtils.format(time, "HH"));
        if (num >= 22) {
            if (!"00:00".equals(DateTimeUtils.format(time, "mm:ss")))
                return new TimeSegmentVO(DateTimeUtils.formatDateToString(DateTimeUtils.nextDate(time, "日", 1))
                        , 0);
            else
                return new TimeSegmentVO(DateTimeUtils.formatDateToString(time), 22);
        }
        for (DateListVO dateListVO : getDateList()) {
            if (dateListVO.getEndTime() != 0 && num >= dateListVO.getStartTime() && num < dateListVO.getEndTime()) {
                return new TimeSegmentVO(DateTimeUtils.formatDateToString(time), dateListVO.getEndTime());
            }
        }
        return null;
    }

    /**
     * 获取时间组
     *
     * @return
     */
    public List<DateListVO> getDateList() {
        return new ArrayList<DateListVO>() {{
            add(new DateListVO(4, 6, 8));
            add(new DateListVO(5, 8, 10));
            add(new DateListVO(6, 10, 12));
            add(new DateListVO(7, 12, 14));
            add(new DateListVO(8, 14, 16));
            add(new DateListVO(9, 16, 18));
            add(new DateListVO(10, 18, 20));
            add(new DateListVO(11, 20, 22));
            add(new DateListVO(12, 22, 0));
            add(new DateListVO(13, 0, 2));
            add(new DateListVO(14, 2, 4));
            add(new DateListVO(15, 4, 6));
        }};
    }

    /**
     * 获取抄表数据
     *
     * @param meterReadingEnum 机组
     * @param autoTime         时间
     * @return
     */
    public Map<Integer, List<DataVO>> getAutomaticTable_New(MeterReadingEnum meterReadingEnum, String autoTime) {
        Map<Integer, List<DataVO>> map = new HashMap<>();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("nowTime", autoTime);
        queryParam.getSqlMap().put("meterReadingEnum", meterReadingEnum.getCode());
        List<AutomaticDayData> automaticDayDataList = automaticDayDataBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(automaticDayDataList)) {
            for (AutomaticDayData automaticDayData : automaticDayDataList) {
                AutomaticModel automaticModel = automaticDayData.getAutomaticModel();
                if (automaticModel == null) {
                    continue;
                }
                List<DataVO> data1 = getDataVOByMap(map, automaticModel.getContentIndex());
                data1.add(new DataVO(automaticModel.getTimeIndex(), automaticDayData.getValue(), FieldType.Text, automaticModel.isAbnormal()));
                map.put(automaticModel.getContentIndex(), data1);
            }
        }
        return map;
    }

    /**
     * 获取抄表数据--旧的，没用了
     *
     * @param meterReadingEnum 机组
     * @param autoTime         时间
     * @return
     */
    public Map<Integer, List<DataVO>> getAutomaticTable(MeterReadingEnum meterReadingEnum, String autoTime) {
        Date date = StringConverters.ToDateOnly(autoTime);
        Date yesterday = DateTimeUtils.nextDate(date, "日", -1);
        Map<Integer, List<DataVO>> map = new HashMap<>();
        Map<String, String> queryHash = new HashMap<>();
        queryHash.put("auto_time", autoTime);
        queryHash.put("yesterday", DateTimeUtils.formatDateToString(yesterday));
        queryHash.put("meter_reading_enum", meterReadingEnum.getCode());
        List objects = dao.getAutomaticTable(queryHash);
        if (CollectionUtils.isNotEmpty(objects)) {
            for (Object object : objects) {
                net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                Integer time_index = AnalysisObjectList.getJsonInteger(j, 2);
                Integer content_index = AnalysisObjectList.getJsonInteger(j, 3);
                String value = AnalysisObjectList.getJsonString(j, 4);
                List<DataVO> data1 = getDataVOByMap(map, content_index);
                data1.add(new DataVO(time_index, value, FieldType.Text, false));
                map.put(content_index, data1);
            }
        }
        return map;
    }

    private List<DataVO> getDataVOByMap(Map<Integer, List<DataVO>> map, Integer index) {
        List<DataVO> list = map.get(index);
        if (CollectionUtils.isEmpty(list)) {
            map.put(index, new ArrayList<>());
            return new ArrayList<>();
        } else {
            return list;
        }
    }

}
